/*
 * The MIT License
 * Copyright (c) 2012 kc4.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.kc4.sso.auth.section.client;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.arnx.jsonic.JSON;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.kc4.sso.auth.SSOClientInitParameters;
import org.kc4.sso.auth.SSOContextParameters;
import org.kc4.sso.auth.section.InterruptedSectionException;
import org.kc4.sso.auth.section.ModelSection;
import org.kc4.sso.crypto.SSOAsymmetricCipher;
import org.kc4.sso.crypto.SSOSymmetricCipher;

/**
 * @author yoichi kikuchi
 *
 */
public class SucceededSignonOnInvalidUserObjectSection extends ModelSection {

	/**
	 * インスタンスを生成します。
	 *
	 * @param request リクエスト。
	 * @param response レスポンス。
	 */
	public SucceededSignonOnInvalidUserObjectSection(HttpServletRequest request, HttpServletResponse response) {

		super(request, response);
	}

	@Override
	public void execute() throws InterruptedSectionException {

		HttpSession session = this.getRequest().getSession();
		SSOAsymmetricCipher asymCipher = (SSOAsymmetricCipher) session.getAttribute(SSOContextParameters.getInstance().getNamingOfAsymmetricCipher());

		if (asymCipher != null) {

			// ユーザーオブジェクト無効 > 暗号器有効
			try {

				String authToken = this.getRequest().getParameter(SSOContextParameters.getInstance().getNamingOfAuthorizationToken());
				String encComkey = this.getRequest().getParameter(SSOContextParameters.getInstance().getNamingOfEncryptedCommonkey());

				if (authToken == null || encComkey == null) {

					return;
				}

				HttpClient client = new DefaultHttpClient();
				client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, SSOContextParameters.getInstance().getProxy());
				HttpPost post = new HttpPost(SSOContextParameters.getInstance().getProviderURL());
				List<NameValuePair> pairs = new ArrayList<NameValuePair>();
				pairs.add(new BasicNameValuePair(SSOContextParameters.getInstance().getNamingOfAuthorizationToken(), authToken));
				post.setEntity(new UrlEncodedFormEntity(pairs));
				HttpResponse httpres = client.execute(post);
				BufferedReader reader = new BufferedReader(new InputStreamReader(
					new BufferedInputStream(httpres.getEntity().getContent())));
				StringBuilder b = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {

					b.append(line);
				}
				String encContent = b.toString();

				byte[] comkey = asymCipher.decrypt(encComkey);
				SSOSymmetricCipher symCipher = new SSOSymmetricCipher(comkey);
				String jsonContent = symCipher.decryptAsString(encContent);
				Serializable userObject = JSON.decode(jsonContent, SSOClientInitParameters.getInstance().getUserObject());

				if (userObject == null) {

					this.sendError(HttpServletResponse.SC_BAD_REQUEST);
					throw new InterruptedSectionException(true);
				}

				/*
				 * ユーザーオブジェクト無効 > 暗号器有効 > 復号成功
				 */
				session.setAttribute(SSOContextParameters.getInstance().getNamingOfUserObject(), userObject);
				session.setAttribute(SSOContextParameters.getInstance().getNamingOfAuthorizationToken(), authToken);
				throw new InterruptedSectionException(false);
			}
			catch (IOException e) {

				throw new IllegalStateException(e);
			}
		}
	}
}
